package com.toman.wifi.Activity;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.net.ConnectivityManager;
import android.net.NetworkInfo;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.Toast;

import com.toman.MyApplication;
import com.toman.R;
import com.toman.Util.StatusBarUtils;
import com.toman.wifi.Activity.task.__IEsptouchTask;

import java.util.List;

public class EsptouchDemoActivity extends Activity implements OnClickListener {

    private static final String TAG = "EsptouchDemoActivity";


    private TextView mTvApSsid;

    private EditText mEdtApPassword;

    private Button mBtnConfirm;

    private EspWifiAdminSimple mWifiAdmin;

    private Spinner mSpinnerTaskCount;

    //布局
    LinearLayout mNoWifis;
    LinearLayout mYesWifi;

    //wifi是否打开
    ConnectivityManager connectivityManager;
    NetworkInfo networkInfo;

    boolean isConnected;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.ccactivity);
        StatusBarUtils.setWindowStatusBarColor(this, R.color.loginbg);
        mWifiAdmin = new EspWifiAdminSimple(this);
        initSpinner();
        initView();
    }


    /*
        初始化控件
     */
    public void initView() {
        findViewById(R.id.mBack).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        // 没有搜索到wifi布局
        mNoWifis = (LinearLayout) findViewById(R.id.mNoWifi);
        //有搜索到wifi连接的布局
        mYesWifi = (LinearLayout) findViewById(R.id.mYesWifi);
        //配置按钮||重新搜索
        mBtnConfirm = (Button) findViewById(R.id.btnConfirm);
        mBtnConfirm.setOnClickListener(this);
        //wifi名称
        mTvApSsid = (TextView) findViewById(R.id.tvApSssidConnected);
        //wifi密码
        mEdtApPassword = (EditText) findViewById(R.id.edtApPassword);

        MyApplication myApplication = (MyApplication) getApplication();
        LinearLayout mCc_bg = (LinearLayout) findViewById(R.id.mCc_bg);
        LinearLayout mCc_Lin1 = (LinearLayout) findViewById(R.id.mCc_Lin1);
        LinearLayout mCc_Lin2 = (LinearLayout) findViewById(R.id.mCc_Lin2);

        if (myApplication.getSp().getString("token", "").equals("toman")) {
            StatusBarUtils.setWindowStatusBarColor(this, R.color.loginbg);
            mCc_bg.setBackgroundResource(R.color.loginbg);
            mCc_Lin1.setBackgroundDrawable(getResources().getDrawable(R.drawable.forgetbg5));
            mCc_Lin2.setBackgroundDrawable(getResources().getDrawable(R.drawable.forgetbg5));
            mBtnConfirm.setBackgroundDrawable(getResources().getDrawable(R.drawable.forgetbg5));
            mEdtApPassword.setBackgroundResource(R.color.forgetcolor);


        } else if (myApplication.getSp().getString("token", "").equals("operater")) {
            StatusBarUtils.setWindowStatusBarColor(this, R.color.myBgn);
            mCc_bg.setBackgroundResource(R.color.myBgn);
            mCc_Lin1.setBackgroundDrawable(getResources().getDrawable(R.drawable.cursor_color1));
            mCc_Lin2.setBackgroundDrawable(getResources().getDrawable(R.drawable.cursor_color1));
            mBtnConfirm.setBackgroundDrawable(getResources().getDrawable(R.drawable.cursor_color1));
            mEdtApPassword.setBackgroundResource(R.color.m2);

        } else if (myApplication.getSp().getString("token", "").equals("company")) {
            StatusBarUtils.setWindowStatusBarColor(this, R.color.c1);
            mCc_bg.setBackgroundResource(R.color.c1);
            mCc_Lin1.setBackgroundDrawable(getResources().getDrawable(R.drawable.cursor_color2));
            mCc_Lin2.setBackgroundDrawable(getResources().getDrawable(R.drawable.cursor_color2));
            mBtnConfirm.setBackgroundDrawable(getResources().getDrawable(R.drawable.cursor_color2));
            mEdtApPassword.setBackgroundResource(R.color.m1);
        }

        connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
        networkInfo = connectivityManager.getActiveNetworkInfo();
        if (networkInfo != null && networkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
            //有打开
            String apSsid = mWifiAdmin.getWifiConnectedSsid();
            if (apSsid != null) {
                mTvApSsid.setText(apSsid);
            }
        } else {
            //没有打开
            mYesWifi.setVisibility(View.GONE);
            mNoWifis.setVisibility(View.VISIBLE);
            mBtnConfirm.setText("重新搜索");
        }
    }


    private void initSpinner() {
        mSpinnerTaskCount = (Spinner) findViewById(R.id.spinnerTaskResultCount);
        int[] spinnerItemsInt = getResources().getIntArray(R.array.taskResultCount);
        int length = spinnerItemsInt.length;
        Integer[] spinnerItemsInteger = new Integer[length];
        for (int i = 0; i < length; i++) {
            spinnerItemsInteger[i] = spinnerItemsInt[i];
        }
        ArrayAdapter<Integer> adapter = new ArrayAdapter<Integer>(this,
                android.R.layout.simple_list_item_1, spinnerItemsInteger);
        mSpinnerTaskCount.setAdapter(adapter);
        mSpinnerTaskCount.setSelection(1);
    }


//	@Override
//	protected void onResume() {
//		super.onResume();
//		// display the connected ap's ssid
//		String apSsid = mWifiAdmin.getWifiConnectedSsid();
//		if (apSsid != null) {
//			mTvApSsid.setText(apSsid);
//		} else {
//			mTvApSsid.setText("");
//		}
//		// check whether the wifi is connected
//		boolean isApSsidEmpty = TextUtils.isEmpty(apSsid);
//		mBtnConfirm.setEnabled(!isApSsidEmpty);
//	}


    @Override
    public void onClick(View v) {
        switch (v.getId()) {
            case R.id.btnConfirm:
                String apSsid = mTvApSsid.getText().toString();
                String apPassword = mEdtApPassword.getText().toString();
                String apBssid = mWifiAdmin.getWifiConnectedBssid();
                if (mBtnConfirm.getText().toString().trim().equals("开始配置")) {
                    if (apPassword.equals("")) {
                        Toast.makeText(this, "请输入密码!", Toast.LENGTH_SHORT).show();
                    } else {
                        connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
                        networkInfo = connectivityManager.getActiveNetworkInfo();
                        if (networkInfo != null && networkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
                        } else {
                            //没有打开wifi
                            Toast.makeText(this, "请连接wifi!", Toast.LENGTH_SHORT).show();
                            mYesWifi.setVisibility(View.GONE);
                            mNoWifis.setVisibility(View.VISIBLE);
                            mBtnConfirm.setText("重新搜索");
                            return;
                        }

                        String taskResultCountStr = Integer.toString(mSpinnerTaskCount.getSelectedItemPosition());
                        if (__IEsptouchTask.DEBUG) {
                            Log.i("test", "wifi:" + apBssid + "密码:" + apPassword);
                        }
                        new EsptouchAsyncTask3().execute(apSsid, apBssid, apPassword, taskResultCountStr);


                    }


                } else {
                    connectivityManager = (ConnectivityManager) getSystemService(Context.CONNECTIVITY_SERVICE);
                    networkInfo = connectivityManager.getActiveNetworkInfo();
                    if (networkInfo != null && networkInfo.getType() == ConnectivityManager.TYPE_WIFI) {
                        //有打开
                        isConnected = isWifiConnect();
                        //判断wifi是否连接成功
                        if (isConnected == false) {
                            //wifi还没有连接
                            Toast.makeText(this, "Wifi还没有连接成功，请稍等...", Toast.LENGTH_SHORT).show();

                        } else {
                            //wifi连接
                            Toast.makeText(this, "连接成功,请开始配置", Toast.LENGTH_SHORT).show();
                            String apSsid1 = mWifiAdmin.getWifiConnectedSsid();
                            if (apSsid1 != null) {
                                mTvApSsid.setText(apSsid1);
                            }
                            mYesWifi.setVisibility(View.VISIBLE);
                            mNoWifis.setVisibility(View.GONE);
                            mBtnConfirm.setText("开始配置");
                        }
                    } else {
                        Toast.makeText(EsptouchDemoActivity.this, "请连接wifi!", Toast.LENGTH_SHORT).show();
                    }
                }

                break;
        }


    }


    public boolean isWifiConnect() {
        ConnectivityManager connManager = (ConnectivityManager) getSystemService(CONNECTIVITY_SERVICE);
        NetworkInfo mWifi = connManager.getNetworkInfo(ConnectivityManager.TYPE_WIFI);
        return mWifi.isConnected();
    }


    private class EsptouchAsyncTask2 extends AsyncTask<String, Void, IEsptouchResult> {

        private ProgressDialog mProgressDialog;

        private IEsptouchTask mEsptouchTask;
        // without the lock, if the user tap confirm and cancel quickly enough,
        // the bug will arise. the reason is follows:
        // 0. task is starting created, but not finished
        // 1. the task is cancel for the task hasn't been created, it do nothing
        // 2. task is created
        // 3. Oops, the task should be cancelled, but it is running
        private final Object mLock = new Object();

        @Override
        protected void onPreExecute() {
            mProgressDialog = new ProgressDialog(EsptouchDemoActivity.this);
            mProgressDialog
                    .setMessage("WIFI配置,请等一会儿...");
            mProgressDialog.setCanceledOnTouchOutside(false);
            mProgressDialog.setOnCancelListener(new OnCancelListener() {
                @Override
                public void onCancel(DialogInterface dialog) {
                    synchronized (mLock) {
                        if (__IEsptouchTask.DEBUG) {
                            Log.i(TAG, "progress dialog is canceled");
                        }
                        if (mEsptouchTask != null) {
                            mEsptouchTask.interrupt();
                        }
                    }
                }
            });
            mProgressDialog.setButton(DialogInterface.BUTTON_POSITIVE,
                    "等待...", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                        }
                    });
            mProgressDialog.show();
            mProgressDialog.getButton(DialogInterface.BUTTON_POSITIVE)
                    .setEnabled(false);
        }

        @Override
        protected IEsptouchResult doInBackground(String... params) {
            synchronized (mLock) {
                String apSsid = params[0];
                String apBssid = params[1];
                String apPassword = params[2];
                mEsptouchTask = new EsptouchTask(apSsid, apBssid, apPassword, EsptouchDemoActivity.this);
            }
            IEsptouchResult result = mEsptouchTask.executeForResult();
            return result;
        }

        @Override
        protected void onPostExecute(IEsptouchResult result) {
            mProgressDialog.getButton(DialogInterface.BUTTON_POSITIVE)
                    .setEnabled(true);
            mProgressDialog.getButton(DialogInterface.BUTTON_POSITIVE).setText(
                    "确认");
            // it is unnecessary at the moment, add here just to show how to use isCancelled()
            if (!result.isCancelled()) {
                if (result.isSuc()) {
                    mProgressDialog.setMessage("WIFI连接成功,bssid = "
                            + result.getBssid() + ",Inet 地址 = "
                            + result.getInetAddress().getHostAddress());
                } else {
                    mProgressDialog.setMessage("WIFI连接 失败");
                }
            }
        }
    }


    private void onEsptoucResultAddedPerform(final IEsptouchResult result) {
        runOnUiThread(new Runnable() {

            @Override
            public void run() {
                String text = result.getBssid() + " 连接到无线网络";
                Toast.makeText(EsptouchDemoActivity.this, text,
                        Toast.LENGTH_LONG).show();
            }

        });
    }

    private IEsptouchListener myListener = new IEsptouchListener() {

        @Override
        public void onEsptouchResultAdded(final IEsptouchResult result) {
            onEsptoucResultAddedPerform(result);
        }
    };

    private class EsptouchAsyncTask3 extends AsyncTask<String, Void, List<IEsptouchResult>> {

        private ProgressDialog mProgressDialog;

        private IEsptouchTask mEsptouchTask;

        private final Object mLock = new Object();


        @Override
        protected void onPreExecute() {
            mProgressDialog = new ProgressDialog(EsptouchDemoActivity.this);
            mProgressDialog.setTitle("Wifi配置");
            mProgressDialog.setMessage("WIFI配置,请等一会儿...");
            mProgressDialog.setCanceledOnTouchOutside(false);

            mProgressDialog.setOnCancelListener(new OnCancelListener() {
                @Override
                public void onCancel(DialogInterface dialog) {
                    synchronized (mLock) {
                        if (__IEsptouchTask.DEBUG) {
                            Log.i("test", "进度对话框取消了");
                        }
                        if (mEsptouchTask != null) {
                            mEsptouchTask.interrupt();
                        }
                    }
                }
            });
            mProgressDialog.setButton(DialogInterface.BUTTON_POSITIVE,
                    "等待...", new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int which) {

                        }
                    });
            mProgressDialog.show();
            mProgressDialog.getButton(DialogInterface.BUTTON_POSITIVE).setEnabled(false);
        }

        @Override
        protected List<IEsptouchResult> doInBackground(String... params) {
            int taskResultCount = -1;
            synchronized (mLock) {
                // !!!NOTICE
                String apSsid = mWifiAdmin.getWifiConnectedSsidAscii(params[0]);
                String apBssid = params[1];
                String apPassword = params[2];
                String taskResultCountStr = params[3];
                taskResultCount = Integer.parseInt(taskResultCountStr);
                mEsptouchTask = new EsptouchTask(apSsid, apBssid, apPassword, EsptouchDemoActivity.this);
                mEsptouchTask.setEsptouchListener(myListener);
            }
            List<IEsptouchResult> resultList = mEsptouchTask.executeForResults(taskResultCount);
            return resultList;
        }

        @Override
        protected void onPostExecute(List<IEsptouchResult> result) {
            mProgressDialog.getButton(DialogInterface.BUTTON_POSITIVE)
                    .setEnabled(true);
            mProgressDialog.getButton(DialogInterface.BUTTON_POSITIVE).setText("确认");
            IEsptouchResult firstResult = result.get(0);
            // check whether the task is cancelled and no results received
            if (!firstResult.isCancelled()) {
                int count = 0;
                // max results to be displayed, if it is more than maxDisplayCount,
                // just show the count of redundant ones
                final int maxDisplayCount = 5;
                // the task received some results including cancelled while
                // executing before receiving enough results
                if (firstResult.isSuc()) {
                    StringBuilder sb = new StringBuilder();
                    for (IEsptouchResult resultInList : result) {
                        sb.append("智能终端成功连接WIFI\nbssid:"
                                + resultInList.getBssid()
                                + "\nMac地址:"
                                + resultInList.getInetAddress()
                                .getHostAddress() + "\n");
                        count++;
                        if (count >= maxDisplayCount) {
                            break;
                        }
                    }
                    if (count < result.size()) {
                        sb.append("\nthere's " + (result.size() - count)
                                + " more result(s) without showing\n");
                    }
                    mProgressDialog.setMessage(sb.toString());
                } else {
                    mProgressDialog.setMessage("WIFI连接 失败");
                }
            }
        }
    }
}
